package com.es.listener; /**
 * 描述:
 * es-servlet-
 *
 * @author Derek
 * 创建时间：2022-04-22 11:52
 */

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.util.*;

@WebListener
public class OnlinesListener implements HttpSessionActivationListener,  HttpSessionListener,ServletRequestListener {
    Set<String> set = new HashSet<>();
    public OnlinesListener() {
    }


    @Override
    public void sessionCreated(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        //
        System.out.println("session创建了");
        Integer count = (Integer) application.getAttribute("count");
        if(count == null){
            application.setAttribute("count", 1);
        }else{
            application.setAttribute("count", count+1);
        }
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        //
        Integer count = (Integer) application.getAttribute("count");

        if(count == null){
            application.setAttribute("count", 0);
        }else{
            application.setAttribute("count", count-1);
        }
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        set.add(sre.getServletRequest().getRemoteAddr());
        ServletContext application = sre.getServletRequest().getServletContext();
        application.setAttribute("set", set);
    }

    @Override
    public void sessionDidActivate(HttpSessionEvent se) {
        ServletContext application = se.getSession().getServletContext();
        //
        Integer count = (Integer) application.getAttribute("count");

        if(count == null){
            application.setAttribute("count", 0);
        }else{
            application.setAttribute("count", count-1);
        }
    }
}
